########################################################################################

library(data.table)
library(RColorBrewer)
library(ggplot2)
library(argparser)
library(dplyr)

##############################################################################

argp <- arg_parser("Plot the deconstructSigs")
argp <- add_argument(argp, "--work_dir" , help="")
argp <- add_argument(argp, "--images_path" , help="")
argp <- add_argument(argp, "--base_line_file" , help="")


argv <- parse_args(argp)

work_dir <- argv$work_dir
images_path <- argv$images_path
base_line_file <- argv$base_line_file

if(1!=1){

  work_dir <- "~/20220915_gastric_multiple/dna_combine_20221213/sigProfiler/decompose"
  images_path <- "~/20220915_gastric_multiple/dna_combine_20221213/sigProfiler/plot"
  base_line_file <- "~/20220915_gastric_multiple/dna_combine_20221213/config/tumor_normal.class.list"

}

##############################################################################

dir.create(images_path , recursive = T)

dat_info <- data.frame(fread(base_line_file))
dat_info$tumor_id <- paste0(dat_info$Tumor , "_" , dat_info$Normal)
tumor_id <- dat_info$tumor_id

##############################################################################
## 读取突变信号
share_list <- c("all" , "trunk" , "private")
class_order <- c("IM\n(IGC)" , "IM\n(DGC)" , "IM\n(IGC_DGC)")

##############################################################################

dat_info <- subset( dat_info , Class == "IM" )
dat_info$Class <- ifelse( dat_info$Type == "IM + IGC" , "IM\n(IGC)" , dat_info$Class )
dat_info$Class <- ifelse( dat_info$Type == "IM + DGC" , "IM\n(DGC)" , dat_info$Class )
dat_info$Class <- ifelse( dat_info$Type == "IM + IGC + DGC" , "IM\n(IGC_DGC)" , dat_info$Class )

##############################################################################

dat_combine_SBS <- c()

for( share in share_list ){
	dat_allSBS <- fread(paste0(work_dir , "/" , share , "_SBS96.txt"))
	dat_allSBS <- subset( dat_allSBS , Samples %in% tumor_id )
	dat_allSBS <- melt(dat_allSBS)
	dat_allSBS$Type <- share
	dat_allSBS <- merge( dat_allSBS , dat_info[,c("tumor_id" , "Class")] , by.x = "Samples" , by.y = "tumor_id" )

	dat_combine_SBS <- rbind( dat_combine_SBS , data.frame(dat_allSBS) )
}
## 存在S_的样本名字
dat_combine_SBS$Samples <- gsub( "S_" , "S" , dat_combine_SBS$Samples)

## 计算占比
dat_combine_SBS_ratio <- c()
for( share in share_list ){
	for(class in class_order){

		tmp <- subset( dat_combine_SBS , Type == share & Class == class )
		## 拆分Normal
		tmp$Normal <- sapply( strsplit(tmp$Samples , "_") , "[" , 2)
		## 同一患者同一病理类型取中位数
		tmp <- tmp %>%
		group_by( Type , variable , Class , Normal ) %>%
		summarize( value = round(median(value)) )

		tmp <- tmp %>%
		group_by( Type , Class , variable ) %>%
		summarize( values = sum(value) )

		tmp$Exposures <- tmp$values/sum(tmp$values)

		dat_combine_SBS_ratio <- rbind( dat_combine_SBS_ratio , tmp )
	}
}

############################################
## 突变信号在各个类别占比均小于0.01的信号，归为other
all_sig <- dat_combine_SBS_ratio
all_sig$Sig <- all_sig$variable
all_sig$MutNum <- all_sig$values

tmp_exporsure <- all_sig %>%
group_by(Sig , Type , Class) %>%
summarize( Exposures_all = sum(Exposures) )

use_sig <- unique(data.frame(tmp_exporsure[tmp_exporsure$Exposures_all > 0.01,])$Sig)

##############################################################################
## SBS1   SBS5   SBS15  SBS17a SBS17b SBS29  SBS39  SBS3 
## SBS15:Defective DNA mismatch repair
## SBS17a SBS17b SBS39:unknown
## SBS3:Defective homologous recombination-based DNA damage repair 
SBS_Age <- c("SBS1" , "SBS5")
SBS_repair <- c("SBS15" , "SBS3")
SBS_Smoke <- c("SBS29")
SBS_unkown <- c("SBS17a" , "SBS17b" , "SBS39")

sig_order <- c( SBS_Age , SBS_repair , SBS_Smoke , SBS_unkown)
all_sig_use <- subset( all_sig , Sig %in% sig_order )

##############################################################################
## 合并OtherSig
#all_sig <- rbind( all_sig_use , other_sig )
all_sig$Type <- factor(all_sig$Type , levels = share_list , order = T)
all_sig$Class <- factor(all_sig$Class , levels = class_order , order = T)

############################################
## 颜色
col_age <- brewer.pal(8,"PRGn")[1:2]
col_repair <- brewer.pal(8,"Paired")[3:4]
col_smoke <- brewer.pal(8,"Paired")[2]
col_unkown <- brewer.pal(6,"Pastel1")[1:3]

## 分内源性和外源性
SBS_out <- SBS_Smoke
SBS_in <- c(SBS_Age , SBS_repair)

sig_order_new <- c( 
	paste0( SBS_Age  , " (Age)" ) ,
	paste0( SBS_repair[1] , " (Mismatch Repair)" ) ,   
	paste0( SBS_repair[2] , " (Homologous Repair)" ) , 
	paste0( SBS_Smoke , " (Tobacco Chewing)" ) , 
	SBS_unkown 
)

col_sig <- c( col_age , col_repair , col_smoke , col_unkown )
names(col_sig) <- sig_order_new

## 改名
all_sig$Sig_New <- as.character( all_sig$Sig )
all_sig$Sig_New[all_sig$Sig %in% SBS_Smoke] <- paste0( all_sig$Sig[all_sig$Sig %in% SBS_Smoke] , " (Tobacco Chewing)" )
all_sig$Sig_New[all_sig$Sig %in% SBS_repair[1]] <- paste0( all_sig$Sig[all_sig$Sig %in% SBS_repair[1]] , " (Mismatch Repair)" )
all_sig$Sig_New[all_sig$Sig %in% SBS_repair[2]] <- paste0( all_sig$Sig[all_sig$Sig %in% SBS_repair[2]] , " (Homologous Repair)" )
all_sig$Sig_New[all_sig$Sig %in% SBS_Age] <- paste0( all_sig$Sig[all_sig$Sig %in% SBS_Age] , " (Age)" )
all_sig$Sig_New <- factor(all_sig$Sig_New , levels = c(sig_order_new) , order = T)

##############################################################################
## Function
plotSig <- function( images_path = images_path , type = type , all_sig = all_sig , col = col_sig , width = width ){
	## 突变信号总体
	## 比例
	images_name <- paste0(images_path,"/Mutation_Signature.decompose.",type,".IM.ratio.pdf",sep="")
	plot <- ggplot(all_sig,aes(x=Class,y=Exposures,fill=factor(Sig_New))) +
		geom_bar(stat="identity") +
		facet_grid(.~Type) +
		xlab(NULL) +
		theme_bw() +
	  theme(panel.background = element_blank(),#设置背影为白色#清除网格线
	        legend.position ='right',
	        legend.title = element_blank() ,
	        panel.grid.major=element_line(colour=NA),
	        legend.text = element_text(size = 8,color="black",face='bold'),
	        axis.text.x = element_text(size = 8,color="black",face='bold'),
	        axis.text.y = element_text(size = 8,color="black",face='bold'),
	        axis.title.x = element_text(size = 10,color="black",face='bold'),
	        axis.title.y = element_text(size = 10,color="black",face='bold'),
	        strip.text.x = element_text(size = 15,color="black",face='bold'),
	        axis.line = element_line(size = 0.5))  +
		scale_fill_manual(values=c(col))

	ggsave(file=images_name,plot=plot,width=width,height=6)
}

type="SBS"
plotSig( images_path = images_path , type = type , all_sig = all_sig , col = col_sig , width = 8 )

##############################################################################
## 要讲的信号分开来画
all_sig$rows <- ""
all_sig[all_sig$Sig  %in% SBS_Age , "rows"] <- "Age"
all_sig[all_sig$Sig  %in% c("SBS15" , "SBS3") , "rows"] <- "Repair"

dat_plot <- subset( all_sig , rows != "" )
for(sig in unique(dat_plot$rows) ){

	dat_plot_tmp <- subset( dat_plot , rows == sig )
	images_name <- paste0(images_path,"/Mutation_Signature.decompose.",sig,".IM.ratio.pdf",sep="")

	if(sig=="Age"){
		y_max <- 1
	}else{
		y_max <- 0.5
	}

	plot <- ggplot(dat_plot_tmp,aes(x=Class,y=Exposures,fill=factor(Sig_New))) +
		geom_bar(stat="identity") +
		facet_grid(.~Type) +
		xlab(NULL) +
		theme_bw() +
		ylim(0,y_max) +
	  theme(panel.background = element_blank(),#设置背影为白色#清除网格线
	        legend.position ='right',
	        legend.title = element_blank() ,
	        panel.grid.major=element_line(colour=NA),
	        legend.text = element_text(size = 8,color="black",face='bold'),
	        axis.text.x = element_text(size = 5,color="black",face='bold'),
	        axis.text.y = element_text(size = 8,color="black",face='bold'),
	        axis.title.x = element_text(size = 10,color="black",face='bold'),
	        axis.title.y = element_text(size = 10,color="black",face='bold'),
	        strip.text.x = element_text(size = 15,color="black",face='bold'),
	        axis.line = element_line(size = 0.5))  +
		scale_fill_manual(values=c(col_sig))

	ggsave(file=images_name,plot=plot,width=6,height=4)
}
